﻿using System;
using Microsoft.Expression.Encoder;
using Microsoft.Expression.Encoder.Profiles;

namespace ExpressionAutomation
{
    public class MediaItemCombiner
    {
        public event EventHandler<EncodeProgressEventArgs> OnCombinerProgress;

        public void Combine(string moviePath, string pathToIntro, string pathToOutro, string outputDirectory)
        {
            var job = new Microsoft.Expression.Encoder.Job();

            var mediaItem = new MediaItem(moviePath);

            mediaItem.OutputFormat = new WindowsMediaOutputFormat();

            // Use source video profile if available
            if (mediaItem.SourceVideoProfile != null)
            {
                mediaItem.OutputFormat.VideoProfile = mediaItem.SourceVideoProfile;
            }
            else
            {
                mediaItem.OutputFormat.VideoProfile = new AdvancedVC1VideoProfile()
                {
                    Size = mediaItem.MainMediaFile.VideoStreams[0].VideoSize,
                    Bitrate = new ConstantBitrate(1000)
                };

            }

            // Use source audio profile if available
            if (mediaItem.SourceAudioProfile != null)
            {
                mediaItem.OutputFormat.AudioProfile = mediaItem.SourceAudioProfile;
            }
            else
            {
                mediaItem.OutputFormat.AudioProfile = new WmaAudioProfile();
            }

            // Add all the sources
            job.MediaItems.Add(mediaItem);

            if (!String.IsNullOrEmpty(pathToIntro))
                mediaItem.Sources.Insert(0, new Source(pathToIntro));

            if (!String.IsNullOrEmpty(pathToOutro))
                mediaItem.Sources.Add(new Source(pathToOutro));

            // Set up the progress callback function
            job.EncodeProgress += new EventHandler<EncodeProgressEventArgs>(EncodeProgress);

            // Set the output directory and encode.
            job.OutputDirectory = outputDirectory;

            // Finally encode
            job.Encode();
        }

        private void EncodeProgress(object sender, EncodeProgressEventArgs e)
        {
            if (OnCombinerProgress != null)
            {
                OnCombinerProgress(this, e);
            }
        }
    }
}
